package com.lottery.football.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.htmlparser.tags.LinkTag;
import org.springframework.stereotype.Service;

import com.lottery.football.customTags.Font;
import com.lottery.football.service.PredictionService;
import com.lottery.football.util.ContentParser;
import com.lottery.football.util.Spiders;

@Service(value="predictionService")
public class PredictionServiceImpl implements PredictionService
{
	public boolean getPredictionFile(String url)
	{
		boolean result = false;
		String html = Spiders.get(url);
		// System.out.println(html);
		// locate font tag whos class is red and text is 下载
		Font font = ContentParser.parseTag(html, Font.class, "class", "red");	
		if (font != null)
		{
			try
			{
				// find <a> tag and download txt file
				String fileUrl = ((LinkTag)(font.searchFor(LinkTag.class, false).elementAt(0))).getAttribute("href");
				CloseableHttpClient httpclient = HttpClients.createDefault();
				HttpGet httpGet = new HttpGet(fileUrl);
				CloseableHttpResponse response = httpclient.execute(httpGet);
				StatusLine status = response.getStatusLine();
				HttpEntity entity = response.getEntity();
				if (status.getStatusCode() == 200 && entity != null)
				{
					InputStream is = entity.getContent();
					FileOutputStream out = new FileOutputStream(new File("E:\\prediction.txt"));  
		             
		            byte[] b = new byte[10240];  
		            int len = 0;  
		            while((len=is.read(b))!= -1){  
		                out.write(b,0,len);  
		            }  
		            is.close();  
		            out.flush();
		            out.close();  
				}
				
				result = true;
			}
			catch (SocketTimeoutException e)
			{
				e.printStackTrace();
			}
			catch (ClientProtocolException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}

		}
		
		return result;
	}
}
